package cn.caplike.demo.repository.design.pattern.proxy.cglib.sample;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;

public class CglibProxy implements MethodInterceptor {
    private final Object target;

    public CglibProxy(Object target) {
        this.target = target;
    }

    @Override
    public Object intercept(Object proxy, Method method, Object[] arguments, MethodProxy methodProxy) throws Throwable {
        if (method.getName().equals("toString"))
            return method.invoke(target, arguments);

        System.out.println("### before invocation");
        final Object result = method.invoke(target, arguments);
        System.out.println("### end invocation");
        return result;
    }

    public static Object getProxy(Object target) {
        final Enhancer enhancer = new Enhancer();
        // 设置需要代理的对象
        enhancer.setSuperclass(target.getClass());
        // 设置代理人
        enhancer.setCallback(new CglibProxy(target));
        return enhancer.create();
    }
}
